package com.mlz.mlzmall.wxapi;


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import com.google.gson.Gson;
import com.mlz.mlzmall.R;
import com.mlz.mlzmall.ui.activity.act.personal.userLogin.GetSession;
import com.mlz.mlzmall.ui.activity.act.personal.userLogin.LoginActivity;
import com.mlz.mlzmall.ui.activity.act.personal.userLogin.ResponseGetToken;
import com.mlz.mlzmall.ui.activity.act.personal.userLogin.ResposeGetPersonInfo;
import com.mlz.mlzmall.ui.model.StringTools;
import com.mlz.mlzmall.ui.utils.mlz.Constans;
import com.mlz.mlzmall.ui.utils.util.ACache;
import com.tencent.mm.sdk.modelbase.BaseReq;
import com.tencent.mm.sdk.modelbase.BaseResp;
import com.tencent.mm.sdk.modelmsg.SendAuth;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.Charset;
import java.util.ArrayList;


public class WXEntryActivity extends Activity implements IWXAPIEventHandler {

    private IWXAPI api;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.autho_login);
        api = WXAPIFactory.createWXAPI(this, Constans.APP_ID, false);
        api.handleIntent(getIntent(), this);
        // 回退到登录页面
        setListener();

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        api.handleIntent(intent, this);
    }

    @Override
    public void onReq(BaseReq req) {


    }

    @Override
    public void onResp(BaseResp resp) {

        // 三方登录回调
        System.out.println("!@#微信分享类型：：" + resp.getType());
        switch (resp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                System.out.println("!@#99999999");
                StringTools.shareback = 101;
//                ShareActivity shareActivity = new ShareActivity();
//                shareActivity.shareSuccese(new CompleteHandler(this),getApplication());
                //接入指南里要拿到的code
                if (StringTools.TYPE != 100) {
                    String code = ((SendAuth.Resp) resp).code;
                    Log.i("info", "code==>" + code);
                    // 通过code获取access_token
                    String getToeknUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + Constans.APP_ID + "&secret=" + Constans.SECRET +
                            "&code=" + code + "&grant_type=authorization_code";
                    getToken(getToeknUrl);
                }
                finish();
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                finish();
                //分享取消
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                //分享拒绝
                finish();
                break;

        }

    }

    private void getToken(final String url) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                // 创建一个restTemplate 对象
                RestTemplate restTemplate = new RestTemplate();
                HttpHeaders requestHeaders = new HttpHeaders();
                requestHeaders.setContentType(new MediaType("application", "json"));
                restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName("UTF-8")));
                // 把请求头放在请求实体里
                HttpEntity<?> requestEntity = new HttpEntity<Object>(requestHeaders);
                ResponseEntity<String> getToken = restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class);
                // 通过Gson 间接转换为对象
                Gson gson = new Gson();
                ResponseGetToken responseGetToken = gson.fromJson(getToken.getBody().toString(), ResponseGetToken.class);
                Log.i("info", "responseGetToken.getScope----->" + responseGetToken.getScope().toString());
                // 获取用户个人信息（UnionID机制）

                String getPersonUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + responseGetToken.getAccess_token() + "&openid=" + responseGetToken.getOpenid();
                ResponseEntity<String> getPersonInfo = restTemplate.exchange(getPersonUrl, HttpMethod.GET, requestEntity, String.class);
                Log.i("info", "getPersonInfo----->" + getPersonInfo.getBody().toString());


                ResposeGetPersonInfo resposeGetPersonI = gson.fromJson(getPersonInfo.getBody().toString(), ResposeGetPersonInfo.class);
                Log.i("info", "resposeGetPersonI----->" + resposeGetPersonI.toString());

                // 先拿到sessionKeyAuth 登录 或者 绑定（未绑定的用户）

                String sessionUrl = "http://app.mlzmall.com/mlzmall/api/session/getSession";
                GetSession urlSession = restTemplate.getForObject(sessionUrl, GetSession.class);
                String sessionKey = urlSession.getData().getSessionKey();
                //  把sessionKey 字符串保存到手机内部存储卡
                ACache mCache = ACache.get(getApplication());
                // 存放时间设定为1天,默认数量为1，更新会覆盖前面的值
                if (sessionKey != null) {
                    mCache.put("sessionKeyAuth", sessionKey, ACache.TIME_DAY);
                }

                // 绑定微信登陆账号 ： 把需要的参数传过去
                Intent intent = new Intent(WXEntryActivity.this, LoginActivity.class);
                intent.setAction("FROM_WX_ENTRY_ACTIVITY");
                ArrayList data = new ArrayList<>();
                data.add(resposeGetPersonI);
                intent.putCharSequenceArrayListExtra("data", data);
                startActivity(intent);
                finish();
            }
        }).start();
    }

    // 回退到登录窗口
    private void setListener() {
        findViewById(R.id.backToLoginFromWX).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(WXEntryActivity.this, LoginActivity.class));
                finish();
            }
        });
    }
}